package com.yunwaikeji.gy_tool_library.widget;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.yunwaikeji.gy_tool_library.info.GYPopupWindowInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 地区选择
 */
public class GYUrbanAreaPw {
    private Context context;
    private OptionsPickerView pvOptions;
    //  省份
    ArrayList<String> provinceBeanList = new ArrayList<>();
    //  城市
    ArrayList<String> cities;
    ArrayList<List<String>> cityList = new ArrayList<>();
    //  区/县
    ArrayList<String> district;
    ArrayList<List<String>> districts;
    ArrayList<List<List<String>>> districtList = new ArrayList<>();

    private int option1 = 0;
    private int option2 = 0;
    private int option3 = 0;

    private GYPopupWindow popupWindow;

    public GYUrbanAreaPw(Context context) {
        this.context = context;
        initData();
        // 初始化Json对象
        initJsonData();
        //初始化Picker
    }

    public GYUrbanAreaPw setLabels(String province, String city, String districtCounty) {
        this.province = province;
        this.city = city;
        this.districtCounty = districtCounty;
        for (int i = 0; i < provinceBeanList.size(); i++) {
            if (provinceBeanList.get(i).equals(province)) {
                option1 = i;
                for (int j = 0; j < cityList.get(i).size(); j++) {
                    if (cityList.get(i).get(j).equals(city)) {
                        option2 = j;
                        for (int k = 0; k < districtList.get(i).get(j).size(); k++) {
                            if (districtList.get(i).get(j).get(k).equals(districtCounty)) {
                                option3 = k;
                            }
                        }
                    }
                }
            }
        }
        return this;
    }

    /**
     * 确认按钮文字颜色
     *
     * @param color
     * @return
     */
    public GYUrbanAreaPw setSubmitColor(int color) {
        submitColor = color;
        return this;
    }

    /**
     * 确认按钮文字
     *
     * @param text
     * @return
     */
    public GYUrbanAreaPw setSubmitText(String text) {
        submitText = text;
        return this;
    }

    /**
     * 取消按钮文字颜色
     *
     * @param color
     * @return
     */
    public GYUrbanAreaPw setCancelColor(int color) {
        cancelColor = color;
        return this;
    }

    /**
     * 取消按钮文字
     *
     * @param text
     * @return
     */
    public GYUrbanAreaPw setCancelText(String text) {
        cancelText = text;
        return this;
    }

    private String province;
    private String city;
    private String districtCounty;
    private int submitColor = Color.BLACK;
    private int cancelColor = Color.BLACK;
    private String submitText = "确定";
    private String cancelText = "取消";

    public GYUrbanAreaPw build() {
        showPicker();
        return this;
    }

    public void show(String province, String city, String districtCounty) {
        if (popupWindow != null) {
            setLabels(province, city, districtCounty);
            pvOptions.setSelectOptions(option1, option2, option3);
            pvOptions.setTitleText((TextUtils.isEmpty(province) ? provinceBeanList.get(option1) : province) + " " + (TextUtils.isEmpty(city) ? cityList.get(option1).get(option2) : city) + " " + (TextUtils.isEmpty(districtCounty) ? districtList.get(option1).get(option2).get(option3) : districtCounty));
            popupWindow.show();
        }
    }

    public void show() {
        if (popupWindow != null) {
            popupWindow.show();
        }
    }

    public View getView() {
        View view = new View(context);
        view.setLayoutParams(new RelativeLayout.LayoutParams(300, 120));
        view.setClickable(true);

        RelativeLayout relativeLayout = new RelativeLayout(context);
        relativeLayout.addView(pvOptions.getDialog().getWindow().getDecorView());
        relativeLayout.addView(view);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        return relativeLayout;
    }

    private TextView newText(String text) {
        TextView textView = new TextView(context);
        textView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(18);
        textView.setTextColor(Color.BLACK);
        textView.setText(text);
        return textView;
    }

    private void initData() {
        popupWindow = new GYPopupWindow(context);
        popupWindow.getViewSet()
                .setWidthProportion(1)
                .setLocation(GYPopupWindowInfo.Location.WINDOW_BOTTOM_CENTER);
    }

    public GYUrbanAreaPw setOnSelectListener(OnSelectListener onSelectListener) {
        this.onSelectListener = onSelectListener;
        return this;
    }

    private OnSelectListener onSelectListener;

    public interface OnSelectListener {
        void onSelectChoose(String province, String city, String districtCounty);

        void onSelectClick(String province, String city, String districtCounty);
    }

    private String s1;
    private String s2;
    private String s3;

    private void showPicker() {
        pvOptions = new OptionsPickerBuilder(context, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                s1 = provinceBeanList.get(options1);
                s2 = cityList.get(options1).get(options2);
                s3 = districtList.get(options1).get(options2).get(options3);
                if (onSelectListener != null) {
                    onSelectListener.onSelectClick(s1, s2, s3);
                }
                popupWindow.dismiss();
            }
        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                        s1 = options1 < provinceBeanList.size() ? provinceBeanList.get(options1) : "";
                        s2 = cityList.get(options1).get(options2);
                        s3 = options3 < districtList.get(options1).get(options2).size() ? districtList.get(options1).get(options2).get(options3) : "";
                        if (onSelectListener != null) {
                            onSelectListener.onSelectChoose(s1, s2, s3);
                        }
                        pvOptions.setTitleText(s1 + " " + s2 + " " + s3);
                    }
                }).setSubmitText(submitText)//确定按钮文字
                .setCancelText(cancelText)//取消按钮文字
                .setTitleText((TextUtils.isEmpty(province) ? provinceBeanList.get(option1) : province) + " " + (TextUtils.isEmpty(city) ? cityList.get(option1).get(option2) : city) + " " + (TextUtils.isEmpty(districtCounty) ? districtList.get(option1).get(option2).get(option3) : districtCounty))//标题
                .setSubCalSize(18)//确定和取消文字大小
                .setTitleSize(14)//标题文字大小
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(submitColor)//确定按钮文字颜色
                .setCancelColor(cancelColor)//取消按钮文字颜色
                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
                .setContentTextSize(18)//滚轮文字大小
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(option1, option2, option3)  //设置默认选中项
                .setOutSideCancelable(false)//点击外部dismiss default true
                .isDialog(true)//是否显示为对话框样式
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .build();

        pvOptions.setPicker(provinceBeanList, cityList, districtList);//添加数据源

        s1 = provinceBeanList.get(0);
        s2 = cityList.get(0).get(0);
        s3 = districtList.get(0).get(0).get(0);

        popupWindow.getViewSet().setViews(getView());
//        popupWindow.dismissCancel();
    }

    private void initJsonData() {
        //解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */

        String JsonData = getJson("province.json");//获取assets目录下的json文件数据
        parseJson(JsonData);
    }

    /**
     * 从asset目录下读取fileName文件内容
     *
     * @param fileName 待读取asset下的文件名
     * @return 得到省市县的String
     */
    private String getJson(String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


    /**
     * 解析json填充集合
     *
     * @param str 待解析的json，获取省市县
     */
    private void parseJson(String str) {
        try {
            //  获取json中的数组
            JSONArray jsonArray = new JSONArray(str);
            //  遍历数据组
            for (int i = 0; i < jsonArray.length(); i++) {
                //  获取省份的对象
                JSONObject provinceObject = jsonArray.optJSONObject(i);
                //  获取省份名称放入集合
                String provinceName = provinceObject.getString("name");
//                provinceBeanList.gylibrary_add(new ProvinceBean(provinceName));
                provinceBeanList.add(provinceName);
                //  获取城市数组
                JSONArray cityArray = provinceObject.optJSONArray("city");
                cities = new ArrayList<>();
                //   声明存放城市的集合
                districts = new ArrayList<>();
                //声明存放区县集合的集合
                //  遍历城市数组
                for (int j = 0; j < cityArray.length(); j++) {
                    //  获取城市对象
                    JSONObject cityObject = cityArray.optJSONObject(j);
                    //  将城市放入集合
                    String cityName = cityObject.optString("name");
                    cities.add(cityName);
                    district = new ArrayList<>();
                    // 声明存放区县的集合
                    //  获取区县的数组
                    JSONArray areaArray = cityObject.optJSONArray("area");
                    //  遍历区县数组，获取到区县名称并放入集合
                    for (int k = 0; k < areaArray.length(); k++) {
                        String areaName = areaArray.getString(k);
                        district.add(areaName);
                    }
                    //  将区县的集合放入集合
                    districts.add(district);
                }
                //  将存放区县集合的集合放入集合
                districtList.add(districts);
                //  将存放城市的集合放入集合
                cityList.add(cities);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

//    @Override
//    public void onBackPressed() {
//        Intent intent = new Intent(this, PersonalProfileActivity.class);
//        intent.putExtra("region", region);
//        setResult(PersonalProfileActivity.RESULT_REGION, intent);
//        super.onBackPressed();
//    }
}
